package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.customerview.adapter.BottomDialogAdapter
import com.zat.mes.andrmes.data.*
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.main.vm.BindMachineModel
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.dofun.work.vm.MachineDayCareModel
import com.zat.mes.andrmes.dofun.work.vm.MachineWeekCareModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.*
import kotlinx.android.synthetic.main.activity_mac_day_care_add.*
import kotlinx.android.synthetic.main.layout_title.*
import kotlinx.android.synthetic.main.layout_title_right_text.view.*
import permissions.dispatcher.*
import java.util.*

@RuntimePermissions
class MacWeekCareAddActivity : BaseActivity() {

    var qcModel: QcPlanViewModel? = null
    var machineDayCareModel: MachineWeekCareModel? = null
    var macDayTypes: MutableList<ParantTypeItem>? = null
    var madModel: BindMachineModel? = null
    var mathineBean: MathineBean? = null
    var mAdapter: BottomDialogAdapter? = null
    var macCareDayBean: MachineCareWeekBean?=null

    override fun init() {
        initView()
        initData()
    }

    private fun initData() {
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        val empId = loginResultBean.empid

        qcModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
        qcModel?.getParantTypeData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it.containsKey("MACHINE_MAINTENANCE_WEEK")) {
                macDayTypes = it.get("MACHINE_MAINTENANCE_WEEK")
            }
        })
        qcModel?.loadParantTypeList("MACHINE_MAINTENANCE_WEEK")
        madModel = ViewModelProvider(this).get(BindMachineModel::class.java)
        //扫码查机器
        madModel?.getMathine()?.observe(this, androidx.lifecycle.Observer {

            if (it == null) {
                showToast("未查到相关机器")
            }
            mathineBean = it
            tvMacCareNo.text = "设备编码：" + mathineBean?.macNo
            //去查询是否有过新增，如果有则修改，如果没有则新增。
            machineDayCareModel?.getMachineCheck(mathineBean?.macNo,
                DateUtil.formatDate(Date(), DateUtil.FORMAT_3),empId.toString())

        })
        mAdapter = BottomDialogAdapter(R.layout.item_dialog_bottom)
        rvMacCareAdd.layoutManager = LinearLayoutManager(this)
        rvMacCareAdd.adapter = mAdapter

        machineDayCareModel = ViewModelProvider(this).get(MachineWeekCareModel::class.java)
        //新增返回
        machineDayCareModel?.getAddMachineData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            showToast(it)
            mathineBean = null
            tvMacCareNo.text = "设备编码"
            mAdapter?.selectList?.clear()
            mAdapter?.notifyDataSetChanged()
        })

        //查询
        machineDayCareModel?.getMachineData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            mAdapter?.setNewData(macDayTypes)
            mAdapter?.selectList?.clear()
            mAdapter?.notifyDataSetChanged()
            if (it==null || it.size<=0){
                btnAddCareMac.text = "新增"
            }else{
                macCareDayBean = it[0]
                try {

                    if(macCareDayBean?.removableReed=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(0)!!)
                    }
                    if(macCareDayBean?.settlerBed=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(1)!!)
                    }
                    if(macCareDayBean?.powerBox=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(2)!!)
                    }
                    if(macCareDayBean?.drawRollerMotor=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(3)!!)
                    }
                    if(macCareDayBean?.organism=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(4)!!)
                    }

                    if(macCareDayBean?.nozzleGuides=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(5)!!)
                    }
                    if(macCareDayBean?.needleBed=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(6)!!)
                    }
                    if(macCareDayBean?.backAndSideDoor=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(7)!!)
                    }
                    if(macCareDayBean?.railAndIndentation=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(8)!!)
                    }
                    if(macCareDayBean?.track=="1"){
                        mAdapter?.selectList?.add(mAdapter?.getItem(9)!!)
                    }
                    mAdapter?.notifyDataSetChanged()
                    btnAddCareMac.text = "修改"
                }catch (e:java.lang.Exception){}

            }
        })
    }

    private fun initView() {
        setContentView(R.layout.activity_mac_week_care_add)
        tVtitle.text = "电机维护周保养"
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
        val inflate = LayoutInflater.from(this).inflate(R.layout.layout_title_right_text, null)
        inflate.tvTitleRight.text = "周保养历史"
        rlRightComm.addView(inflate)
        rlRightComm.visibility = View.VISIBLE
        val layoutParams: RelativeLayout.LayoutParams =
            inflate.layoutParams as RelativeLayout.LayoutParams
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE)
        layoutParams.rightMargin = DisplayUtil.dip2px(this, 30f)
        rlRightComm.setOnClickListener {
            startActivity(Intent(this,MacWeekCareActivity::class.java))
        }
        btnScanMacCareAdd.setOnClickListener {
            showCameraWithPermissionCheck()
        }




        btnAddCareMac.setOnClickListener {

            if (mathineBean == null) {
                showToast("请扫机器码")
                return@setOnClickListener
            }
            //提交
            if (btnAddCareMac.text == "新增") {
                val macDayBean = MachineCareWeekBean()
                macDayBean.machineNo = mathineBean?.macNo
                macDayBean.workDay = DateUtil.formatDate(Date(), DateUtil.FORMAT_3)
                val selectList = mAdapter?.selectList
                for (c in selectList?.indices!!) {
                    when (selectList.get(c).paramenname) {
                        "removableReed" -> macDayBean?.removableReed = "1"
                        "settlerBed" -> macDayBean?.settlerBed = "1"
                        "powerBox" -> macDayBean?.powerBox = "1"
                        "drawRollerMotor" -> macDayBean?.drawRollerMotor = "1"
                        "organism" -> macDayBean?.organism = "1"
                        "nozzleGuides" -> macDayBean?.nozzleGuides = "1"
                        "needleBed" -> macDayBean?.needleBed = "1"
                        "backAndSideDoor" -> macDayBean?.backAndSideDoor = "1"
                        "railAndIndentation" -> macDayBean?.railAndIndentation = "1"
                        "track" -> macDayBean?.track = "1"
                    }
                }
                machineDayCareModel?.addMachineCheck(macDayBean)
            }else{
                //修改
                macCareDayBean?.removableReed = "0"
                macCareDayBean?.settlerBed = "0"
                macCareDayBean?.powerBox = "0"
                macCareDayBean?.drawRollerMotor = "0"
                macCareDayBean?.organism = "0"
                macCareDayBean?.nozzleGuides = "0"
                macCareDayBean?.needleBed = "0"
                macCareDayBean?.backAndSideDoor = "0"
                macCareDayBean?.railAndIndentation = "0"
                macCareDayBean?.track = "0"
                val selectList = mAdapter?.selectList
                for (c in selectList?.indices!!) {
                    when (selectList.get(c).paramenname) {
                        "removableReed" -> macCareDayBean?.removableReed = "1"
                        "settlerBed" -> macCareDayBean?.settlerBed = "1"
                        "powerBox" -> macCareDayBean?.powerBox = "1"
                        "drawRollerMotor" -> macCareDayBean?.drawRollerMotor = "1"
                        "organism" -> macCareDayBean?.organism = "1"
                        "nozzleGuides" -> macCareDayBean?.nozzleGuides = "1"
                        "needleBed" -> macCareDayBean?.needleBed = "1"
                        "backAndSideDoor" -> macCareDayBean?.backAndSideDoor = "1"
                        "railAndIndentation" -> macCareDayBean?.railAndIndentation = "1"
                        "track" -> macCareDayBean?.track = "1"
                    }
                }
                machineDayCareModel?.upDateMachineCheck(macCareDayBean!!)
            }
            showLoading()
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查机器
            showLoading()
            madModel?.selectMacByQr(qrCode);

        }
    }


    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(Intent(this, QrScanActivity::class.java), 0)

        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }
}